<?
ini_set("display_errors",1);
include($_SERVER['DOCUMENT_ROOT'].'/includes/functions.inc.php');
include($_SERVER['DOCUMENT_ROOT'].'/portals/config.php');
include($_SERVER['DOCUMENT_ROOT'].'/groups/database.php');

init_session();

if (empty($_GET['scope']))
	$_GET['scope'] = 'images';


if (empty($_GET['inner'])) {
	include($_SERVER['DOCUMENT_ROOT'].'/portals/header.inc.php');
} else {
	?><html>
	<head>	<link rel="stylesheet" type="text/css" href="/portals/style.css" />
	</head>
	<body><?
}

#########################

print "<H2>Search Portals</h2>";

 if (!empty($_GET['q']) && $_GET['q'] == 'search keywords...') {
 	$_GET['q'] ='';
 }
 
 if (!empty($_GET['q'])) {
  
 	include($_SERVER['DOCUMENT_ROOT'].'/geograph/sphinxwrapper.class.php'); 
 	
 	$CONF['sphinx_host'] = "localhost";
 	$CONF['sphinx_port']= 3312;
 	$CONF['sphinx_index']= "portalimages";
 
 	$q=trim($_GET['q']);
 	
 		$q = preg_replace('/\b(day|month|year):/','taken$1:',$q);
 		$q = preg_replace('/\b(monthname):/','month:',$q);
 		$q = preg_replace('/\b(gridref):/','grid_reference:',$q);
 		$q = preg_replace('/\b(category):/','imageclass:',$q);
 		$q = preg_replace('/\b(description):/','comment:',$q);
 		$q = preg_replace('/\b(name):/','realname:',$q);
 	
 	$sphinx = new sphinxwrapper($q);
 
 	$q = $sphinx->q;
 } else {
 	$q = '';
 }
  
 ?>
 <form method="get" style="background-color:#cccccc;padding:3px;">
 
 	<div>Search: <input type="text" name="q" size="40" value="<? echo htmlentities($sphinx->qclean); ?>">
 	<input type="submit" value="Search"> <br/>
 	
 	Look in: <input type="radio" name="scope" value="portals" id="scopep" checked disabled/> <label for="scopep" style=color:gray>Portal Definition</label> / 
 	<input type="radio" name="scope" value="images" id="scopei" <? if (!empty($_GET['scope']) && $_GET['scope'] == 'images') { echo "checked"; } ?>/> <label for="scopei">Images in Portals</label>.  &nbsp;  &nbsp;  &nbsp;  &nbsp;
 	<!--input type="checkbox" name="go" id="gob" checked/> <label for="gob">if one result, go directly there!</label-->
 	</div>
 </form>
 <?
  
if (!empty($_GET['q'])) {

	


 
	$sphinx->pageSize = $pgsize = 10;

	
	$pg = (!empty($_GET['page']))?intval(str_replace('/','',$_GET['page'])):0;
	if (empty($pg) || $pg < 1) {$pg = 1;}
	
	$cacheid .=".".$pg;
	
		
		$offset = (($pg -1)* $sphinx->pageSize)+1;
		
		if ($offset < (1000-$pgsize) ) { 
			#$sphinx->processQuery();
		
			$cl = $sphinx->_getClient();
			
			if (!empty($_GET['scope']) && $_GET['scope'] == 'images') {
			
				$cl->SetGroupBy('portal_id',SPH_GROUPBY_ATTR,"portal_id DESC");

				$cl->SetArrayResult(true);

				$ids = $sphinx->returnIds($pg,'portalimages');
			
			
			} else {
				$ids = $sphinx->returnIds($pg,'portals');
			}
			
			if ($_GET['d']) {
				print_rp($cl);
				print_rp($sphinx->res);
			}
			
			if (!empty($ids) && count($ids) > 1) {
				
				$sql = array();
				$sql['columns'] = 'gridimage_id,title,realname,user_id,grid_reference,comment,imagetaken,imageclass';
				$sql['tables'] = array();
				
				$sql['tables'][] = "geograph_live.gridimage_search AS gi";
				
				$sql['wheres'] = array();
				if ($cl->_arrayresult) {
					//cos used SetArrayResult ids are just squencial
					
					$gids = array();
					$pids = array();
					foreach ($ids as $idx => $id) {
						$gids[] = $sphinx->res['matches'][$id]['id'];
						$pids[] = $sphinx->res['matches'][$id]['attrs']['@groupby']; //use this rather than portal_id attribute, so its unique.
					}
					$sql['wheres'][] = "gridimage_id IN(".join(",",$gids).")";
				
					$portals = getAssoc("SELECT portal_id,domain,title,realname,user_id FROM `portal` LEFT JOIN user USING (user_id) WHERE status_id = 1 AND public = 'Y' AND portal_id IN (".join(",",$pids).")");
				} else {
					$gids = array(); //TODO...
					$pids = $ids;
					
					$sql['wheres'][] = "gridimage_id IN(".join(",",$gids).")";
					
					$portals = getAssoc("SELECT portal_id,domain,title,realname,user_id,gridimage_id 
						FROM `portal` p LEFT JOIN user USING (user_id) INNER JOIN cluster c USING (portal_id) 
						WHERE status_id = 1 AND public = 'Y' AND p.portal_id IN (".join(",",$pids).") AND c.level = 1
						GROUP BY p.portal_id ORDER BY NULL");
			
				}
			
				
				$sql['order']= 'NULL'; //we going to reorder anyway
				$sql['limit'] = $sphinx->pageSize;

			
				
				
				
				$query = sqlMakeQuery($sql);
				$rows = getAssoc($query);
				
				
				$sphinx->resultCount--; //remove the current portal :)
				
				$final = min($offset+$sphinx->pageSize-1,$sphinx->resultCount);
				print "<div style=\"float:right\">{$offset}..{$final} of {$sphinx->resultCount}</div>";
				
				foreach ($ids as $idx => $id) {
					if ($cl->_arrayresult) {
						//cos used SetArrayResult ids are just squencial
						$gid = $sphinx->res['matches'][$id]['id'];
						$c = $rows[$gid];
						$c['gridimage_id'] = $gid;
						
						$portal_id = $sphinx->res['matches'][$id]['attrs']['@groupby'];
					} else {
						$gid = 
						$c = $rows[$gid];
						$c['gridimage_id'] = $gid;
						
						$portal_id = $id;
					}
					
					
					
					if ($this_portal == $portal_id ) {
						//nothing!
					} elseif ($c) {
					
					?>
					<div style="clear:left; border-top:1px solid #eeeeee">
					  <div style="float:left;position:relative; width:130px; margin-right:10px">
					  <div align="center">
					  <a title="<? ehec('grid_reference'); ?> : <? ehec('title'); ?> by <? ehec('realname'); ?> - click to view full size image" href="http://www.geograph.org.uk/photo/<? echo $c['gridimage_id']; ?>"><img src="<? echo gGUc($c); ?>" width="70%"  /></a></div>
					  </div>

					  <? echo $offset; ?>. <big><b><a href="http://<? echo he($portals[$portal_id]['domain']); ?>.portal.geographs.org/"><? echo he($portals[$portal_id]['title']); ?></a></b></big> by
					  <a href="http://www.geographs.org/portals/profile/<? echo he($portals[$portal_id]['user_id']); ?>"><? echo he($portals[$portal_id]['realname']); ?></a>
					  
					  <br/><br/>
					  
					  
					  
					  <small>(image: <a href="http://www.geograph.org.uk/gridref/<? ehec('grid_reference'); ?>"><tt><? ehec('grid_reference'); ?></tt></a>
					  <a href="http://www.geograph.org.uk/photo/<? echo $c['gridimage_id']; ?>"><? ehec('title'); ?></a>
					   by <a href="<? echo linktoself(array('bi_id'=>$c['user_id'],'delete'=>'page')); ?>"><? ehec('realname'); ?></a></small>)<br/>

					 
					  <br style="clear:left"/>
					</div>
					<?
						$offset++;
					} else {
						?>
						<div style="clear:left; border-top:1px solid #eeeeee">
							 <? echo $offset; ?>. Image <a href="http://www.geograph.org.uk/photo/<? echo $id; ?>">http://www.geograph.org.uk/photo/<? echo $id; ?></a> not available in this portal at the moment.
						</div>
						<?
						$offset++;
					}
					
					
				}
								
				if ($sphinx->resultCount > $sphinx->pageSize) {
					print " &middot; &nbsp; ";
					if ($pg > 1) {
						$last = $pg-1;
						print "<a href=\"search.php?q=".urlencode($sphinx->qclean)."&amp;page=$last\">&lt; &lt; <b>Prev page</b> </a> &nbsp; &middot; ";
					}
					if ($pg < $sphinx->numberOfPages) {
						$next = $pg+1;
						print " &nbsp; <a href=\"search.php?q=".urlencode($sphinx->qclean)."&amp;page=$next\"><b>Next page</b> &gt;&gt;</a> &nbsp; &middot;";
					}
				}
		
				print "<br style='clear:both'><p class=\"message\">{$sphinx->query_info}</p>";
				
				
				
				
				
				
			} else {
				print "<p>No results for your query.</p>";
							
			}
			
			
			
		} else {
			print "Search will only return 1000 results - please refine your search";
		
		}
}

if (empty($_GET['inner'])) {
	include($_SERVER['DOCUMENT_ROOT'].'/portals/footer.inc.php');
}
